package cn.hrc.service.impl;

import cn.hrc.dao.HotMapper;
import cn.hrc.entity.Hot;
import cn.hrc.service.HotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.logging.Logger;

@Service
public class HotServiceImpl implements HotService {
    private Logger logger = Logger.getLogger(HotServiceImpl.class.getName());
    @Autowired
    HotMapper hotMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Override // 查询所有
    public List<Hot> findAll() {
        logger.info("查询所有轮播图");
        logger.info("Redis 查询所有");
        List<Hot> hots = redisTemplate.opsForHash()
                .values("hrc:hot");
        if (hots != null)return hots;
        logger.info("SQL 查询所有");
        hots = hotMapper.selectByMap(null);
        if (hots == null) return null;
        logger.info("Redis 添加所有");
        for (Hot hot : hots) {
            redisTemplate.opsForHash()
                    .put("hrc:hot",hot.getId(),hot);
        }
        // 返回
        return hots;
    }
    @Override // 根据id查询
    public Hot findById(int id) {
        logger.info("Redis 查询");
        Hot hot = (Hot) redisTemplate.opsForHash()
                .get("hrc:hot", id);
        if (hot != null) return hot;
        logger.info("SQL 查询");
        hot = hotMapper.selectById(id);
        if (hot == null) return null;
        logger.info("Redis 添加");
        redisTemplate.opsForHash()
                .put("hrc:hot",hot.getId(),hot);
        return hot;
    }

    @Override
    public void addHot(Hot hot){
        logger.info("SQL 添加");
        int n = hotMapper.insert(hot);
        if (n == 0)return ;
        logger.info("Redis 添加");
        redisTemplate.opsForHash()
                .put("hrc:hot",hot.getId(),hot);
    }

    @Override
    public void updHot(Hot hot) {
        logger.info("Redis 更新前双删");
        redisTemplate.opsForHash()
                .delete("hrc:hot",hot.getId());
        try {
            logger.info("SQL 更新");
            int n = hotMapper.updateById(hot);
            if (n == 0)return;
            Thread.sleep(100);
            logger.info("Redis 更新后双删");
            redisTemplate.opsForHash()
                    .delete("hrc:hot",hot.getId());
            logger.info("Redis 添加");
            redisTemplate.opsForHash()
                    .put("hrc:hot",hot.getId(),hot);
        } catch (InterruptedException e) {
            System.out.println("修改失败");
        }
    }

    @Override
    public void deleteHot(int id) {
        logger.info("SQL 删除");
        hotMapper.deleteById(id);
        logger.info("Redis 删除");
        redisTemplate.opsForHash()
                .delete("hrc:hot",id);

    }
}
